package controller

import (
	"mumu_stock_trad/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 模拟的 Token 和用户信息
var tokens = map[string]struct {
	Token string `json:"token"`
}{
	"admin":  {Token: "admin-token"},
	"editor": {Token: "editor-token"},
}

var users = map[string]struct {
	Roles        []string `json:"roles"`
	Introduction string   `json:"introduction"`
	Avatar       string   `json:"avatar"`
	Name         string   `json:"name"`
}{
	"admin-token": {
		Roles:        []string{"admin"},
		Introduction: "I am a super administrator",
		Avatar:       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		Name:         "Super Admin",
	},
	"editor-token": {
		Roles:        []string{"editor"},
		Introduction: "I am an editor",
		Avatar:       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		Name:         "Normal Editor",
	},
}

// 登录接口
func Login(c *gin.Context) {
	var json struct {
		Username string `json:"username"`
	}

	// 解析请求体
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    40000,
			"message": "Invalid request",
		})
		return
	}

	// 检查用户是否存在
	token, exists := tokens[json.Username]
	if !exists {
		c.JSON(http.StatusOK, gin.H{
			"code":    60204,
			"message": "Account and password are incorrect.",
		})
		return
	}

	jwtToken, _ := util.GenerateToken(json.Username)

	// 返回 token
	c.JSON(http.StatusOK, gin.H{
		"code":  0,
		"data":  token,
		"token": jwtToken,
	})
}

// 获取用户信息接口
func GetUserInfo(c *gin.Context) {
	// 从 query 参数中获取 token
	token := c.DefaultQuery("token", "")

	// 获取用户信息
	userInfo, exists := users[token]
	if !exists {
		c.JSON(http.StatusOK, gin.H{
			"code":    50008,
			"message": "Login failed, unable to get user details.",
		})
		return
	}

	// 返回用户信息
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": userInfo,
	})
}

// 登出接口
func Logout(c *gin.Context) {
	// 返回成功消息
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": "success",
	})
}
